<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" class="search-form">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="消息模板名称">
                            <el-input v-model="searchForm.messageTemplateName" placeholder="请输入消息模板名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="消息模板类型">
                            <el-select v-model="searchForm.messageTemplateType" placeholder="请选择消息模板类型" clearable
                                style="width: 100%">
                                <el-option v-for="item in messageTypeOptions" :key="item.dictValue"
                                    :label="item.dictLabel" :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="是否默认模板">
                            <el-select v-model="searchForm.isDefault" placeholder="请选择" clearable style="width: 100%">
                                <el-option label="是" :value="1" />
                                <el-option label="否" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <div class="form-actions">
                            <el-button type="primary" @click="handleSearch">
                                <el-icon class="el-icon--left">
                                    <Search />
                                </el-icon>
                                查询
                            </el-button>
                            <el-button @click="resetSearch">
                                <el-icon class="el-icon--left">
                                    <Refresh />
                                </el-icon>
                                重置
                            </el-button>

                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 数据表格区域 -->
        <el-card class="table-card mt-2">
            <div class="action-buttons">
                <el-button type="success" @click="handleAdd">
                    <el-icon class="el-icon--left">
                        <Plus />
                    </el-icon>
                    新增
                </el-button>
                <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
                    <el-icon class="el-icon--left">
                        <Delete />
                    </el-icon>
                    批量删除
                </el-button>
                <el-button type="warning" @click="handleExport" :loading="exportLoading">
                    <el-icon class="el-icon--left">
                        <Download />
                    </el-icon>
                    导出
                </el-button>
            </div>

            <el-table :data="tableData" v-loading="loading" border @selection-change="handleSelectionChange"
                class="mt-2">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="messageTemplateId" label="模板ID" width="100" align="center" />
                <el-table-column prop="messageTemplateName" label="模板名称" align="center" min-width="150"
                    show-overflow-tooltip />
                <el-table-column prop="messageTemplateContent" label="模板内容" align="center" min-width="200"
                    show-overflow-tooltip>
                    <template #default="{ row }">
                        <span class="content-text">{{ row.messageTemplateContent || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="messageTemplateType" label="模板类型" align="center" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getTypeTagType(row.messageTemplateType)">
                            {{ getTypeLabel(row.messageTemplateType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="isDefault" label="是否默认" align="center" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.isDefault === 1 ? 'success' : 'info'">
                            {{ row.isDefault === 1 ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="usageCount" label="使用次数" align="center" width="100" sortable>
                    <template #default="{ row }">
                        <span>{{ row.usageCount || 0 }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="creator" label="创建人" align="center" width="120" />
                <el-table-column prop="lastUpdateTime" label="更新时间" align="center" width="180">
                    <template #default="{ row }">
                        {{ formatDateTime(row.lastUpdateTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="updater" label="更新人" align="center" width="120" />
                <el-table-column label="操作" align="center" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link size="small" @click="handleView(row)">
                            查看
                        </el-button>
                        <el-button type="warning" link size="small" @click="handleEdit(row)">
                            编辑
                        </el-button>
                        <el-button type="success" link size="small" @click="handleSetSingleDefault(row)"
                            v-if="row.isDefault === 0">
                            设默认
                        </el-button>
                        <el-button type="danger" link size="small" @click="handleDelete(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :before-close="handleCloseDialog">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="模板名称" prop="messageTemplateName">
                            <el-input v-model="formData.messageTemplateName" placeholder="请输入消息模板名称" maxlength="50"
                                show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="模板类型" prop="messageTemplateType">
                            <el-select v-model="formData.messageTemplateType" placeholder="请选择消息模板类型"
                                style="width: 100%">
                                <el-option v-for="item in messageTypeOptions" :key="item.dictValue"
                                    :label="item.dictLabel" :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="模板编码" prop="smsCode" v-if="formData.messageTemplateType == 0">
                    <el-input v-model="formData.smsCode" placeholder="请输入消息模板编码" maxlength="50" show-word-limit />
                </el-form-item>
                <el-form-item label="模板内容" prop="messageTemplateContent">
                    <el-input v-model="formData.messageTemplateContent" type="textarea" :rows="6"
                        placeholder="请输入消息模板内容" maxlength="500" show-word-limit />
                    <div class="form-tip">支持使用变量，如：{name}、{time}等</div>
                </el-form-item>
                <el-form-item label="是否默认模板">
                    <el-radio-group v-model="formData.isDefault">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                    <div class="form-tip">设置为默认模板后，将作为该类型的默认模板使用</div>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleCloseDialog">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
            </template>
        </el-dialog>

        <!-- 查看详情对话框 -->
        <el-dialog v-model="viewDialogVisible" title="消息模板详情" width="800px">
            <el-descriptions v-if="currentDetail" :column="2" border>
                <el-descriptions-item label="模板ID">{{ currentDetail.messageTemplateId }}</el-descriptions-item>
                <el-descriptions-item label="模板名称">{{ currentDetail.messageTemplateName }}</el-descriptions-item>
                <el-descriptions-item label="模板类型">
                    <el-tag :type="getTypeTagType(currentDetail.messageTemplateType)">
                        {{ getTypeLabel(currentDetail.messageTemplateType) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="是否默认">
                    <el-tag :type="currentDetail.isDefault === 1 ? 'success' : 'info'">
                        {{ currentDetail.isDefault === 1 ? '是' : '否' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="使用次数">{{ currentDetail.usageCount || 0 }}</el-descriptions-item>
                <el-descriptions-item label="创建人">{{ currentDetail.creator || '-' }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="更新人">{{ currentDetail.updater || '-' }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.lastUpdateTime)
                    }}</el-descriptions-item>
                <el-descriptions-item label="模板内容" :span="2">
                    <div class="content-area">
                        <pre>{{ currentDetail.messageTemplateContent || '-' }}</pre>
                    </div>
                </el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <el-button @click="viewDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// API导入
import {
    getMessageTypeDictList,
    getMessageTemplateList,
    getMessageTemplateDetail,
    addMessageTemplate,
    updateMessageTemplate,
    deleteMessageTemplate,
    setDefaultTemplate,
    exportMessageTemplate
} from '@/api/basic/message/template'

// 搜索表单
const searchForm = reactive({
    messageTemplateName: '',
    messageTemplateType: '',
    isDefault: ''
})

// 分页参数
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 表格数据
const tableData = ref([])
const messageTypeOptions = ref([])
const loading = ref(false)
const exportLoading = ref(false)
const selectedRows = ref([])

// 对话框控制
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add') // add/edit
const submitting = ref(false)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
    messageTemplateId: '',
    messageTemplateName: '',
    messageTemplateContent: '',
    messageTemplateType: '',
    isDefault: 0
})

// 当前查看的详情
const currentDetail = ref(null)

// 表单验证规则
const formRules = {
    smsCode: [
        { required: true, message: '请输入消息模板编码', trigger: 'blur' },
    ],
    messageTemplateName: [
        { required: true, message: '请输入消息模板名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    messageTemplateType: [
        { required: true, message: '请选择消息模板类型', trigger: 'change' }
    ],
    messageTemplateContent: [
        { required: true, message: '请输入消息模板内容', trigger: 'blur' },
        { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
    ]
}

// 计算属性
const dialogTitle = computed(() => {
    return dialogType.value === 'add' ? '新增消息模板' : '编辑消息模板'
})

// 初始化数据
onMounted(() => {
    initData()
})

// 初始化数据
const initData = async () => {
    try {
        await Promise.all([
            fetchMessageTypeList(),
            fetchMessageTemplateList()
        ])
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    }
}

// 获取消息类型列表
const fetchMessageTypeList = async () => {
    try {
        const res = await getMessageTypeDictList()
        messageTypeOptions.value = res.data || []
    } catch (error) {
        console.error('获取消息类型列表失败:', error)
        ElMessage.error('获取消息类型列表失败')
    }
}

// 获取消息模板列表
const fetchMessageTemplateList = async () => {
    try {
        loading.value = true
        const params = {
            ...searchForm,
            pageNum: pagination.currentPage,
            pageSize: pagination.pageSize
        }

        const res = await getMessageTemplateList(params)
        tableData.value = res.rows || []
        pagination.total = res.total || 0
    } catch (error) {
        console.error('获取消息模板列表失败:', error)
        ElMessage.error('获取消息模板列表失败')
    } finally {
        loading.value = false
    }
}

// 查询
const handleSearch = () => {
    pagination.currentPage = 1
    fetchMessageTemplateList()
}

// 重置搜索
const resetSearch = () => {
    Object.assign(searchForm, {
        messageTemplateName: '',
        messageTemplateType: '',
        isDefault: ''
    })
    pagination.currentPage = 1
    fetchMessageTemplateList()
}

// 新增
const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
    try {
        const res = await getMessageTemplateDetail(row.messageTemplateId)
        if (res.data) {
            Object.assign(formData, res.data)
            dialogType.value = 'edit'
            dialogVisible.value = true
        }
    } catch (error) {
        console.error('获取消息模板详情失败:', error)
        ElMessage.error('获取消息模板详情失败')
    }
}

// 查看
const handleView = async (row) => {
    try {
        const res = await getMessageTemplateDetail(row.messageTemplateId)
        if (res.data) {
            currentDetail.value = res.data
            viewDialogVisible.value = true
        }
    } catch (error) {
        console.error('获取消息模板详情失败:', error)
        ElMessage.error('获取消息模板详情失败')
    }
}

// 删除
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除消息模板"${row.messageTemplateName}"吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await deleteMessageTemplate([row.messageTemplateId])
        ElMessage.success('删除成功')
        fetchMessageTemplateList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的记录')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const ids = selectedRows.value.map(item => item.messageTemplateId)
        await deleteMessageTemplate(ids)
        ElMessage.success('批量删除成功')
        selectedRows.value = []
        fetchMessageTemplateList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }
}

// 设为默认（单个）
const handleSetSingleDefault = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确定要将"${row.messageTemplateName}"设为默认模板吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await setDefaultTemplate([row.messageTemplateId])
        ElMessage.success('设置成功')
        fetchMessageTemplateList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('设置默认模板失败:', error)
            ElMessage.error('设置默认模板失败')
        }
    }
}

// 批量设为默认
const handleSetDefault = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要设置的记录')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要将选中的 ${selectedRows.value.length} 条记录设为默认模板吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const ids = selectedRows.value.map(item => item.messageTemplateId)
        await setDefaultTemplate(ids)
        ElMessage.success('批量设置成功')
        selectedRows.value = []
        fetchMessageTemplateList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量设置默认模板失败:', error)
            ElMessage.error('批量设置默认模板失败')
        }
    }
}

// 导出
const handleExport = async () => {
    try {
        exportLoading.value = true
        await exportMessageTemplate(searchForm)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    } finally {
        exportLoading.value = false
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitting.value = true

        if (dialogType.value === 'add') {
            await addMessageTemplate(formData)
            ElMessage.success('新增成功')
        } else {
            await updateMessageTemplate(formData)
            ElMessage.success('修改成功')
        }

        dialogVisible.value = false
        fetchMessageTemplateList()
    } catch (error) {
        console.error('提交失败:', error)
        if (error.errors) {
            return
        }
        ElMessage.error('操作失败')
    } finally {
        submitting.value = false
    }
}

// 关闭对话框
const handleCloseDialog = () => {
    dialogVisible.value = false
    resetForm()
}

// 重置表单
const resetForm = () => {
    Object.assign(formData, {
        messageTemplateId: '',
        messageTemplateName: '',
        messageTemplateContent: '',
        messageTemplateType: '',
        isDefault: 0
    })
    if (formRef.value) {
        formRef.value.clearValidate()
    }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 分页处理
const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    fetchMessageTemplateList()
}

const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchMessageTemplateList()
}

// 工具函数
const formatDateTime = (dateTime) => {
    if (!dateTime) return '-'
    try {
        return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
    } catch {
        return dateTime
    }
}

const getTypeTagType = (type) => {
    const types = ['success', 'warning', 'danger', 'info']
    const index = type ? type.charCodeAt(0) % types.length : 0
    return types[index]
}

const getTypeLabel = (type) => {
    if (!type) return '-'
    const typeItem = messageTypeOptions.value.find(item => item.dictValue === type)
    return typeItem ? typeItem.dictLabel : type
}
</script>

<style scoped>

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

</style>